<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button :disabled="!canSave" @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-deptName>
              <el-input
                v-model="formInfo.data.deptName"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择部门"
              >
                <template #append>
                  <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <new-page-filter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!formInfo.data.deptId" @click="addProduct()"
                >添加产品</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品</el-button
              >
            </template>
          </new-page-filter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            v-if="scope.$index >= 0"
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="99999999"
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item v-if="scope.$index >= 0">
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}[price]`"
                    :rules="
                      scope.$index >= 0
                        ? {
                            validator: $validate.positiveMoneyZero,
                            trigger: 'blur',
                          }
                        : {}
                    "
                  >
                    <el-input-number
                      v-model="scope.row.price"
                      controls-position="right"
                      style="minwidth: 100px; margintop: 18px"
                      :precision="systemConfig.price_precision"
                      :step="1"
                      :min="0"
                      :max="999999999999999"
                      @change="
                        changePrice($event, `data.${scope.$index}.price`)
                      "
                    />
                    <p
                      style="color: red"
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.price > scope.row.purchaseLimitPrice
                      "
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
          <!--新产品选择框-->
          <NewSelectProduct
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            :query="productInfo.query.queryMap"
            :table-key="productInfo.tableKey"
            :sort-string="productInfo.sortString"
            :query-params="productInfo.query.queryParams"
            :show-price="$permission('otherTemplate:price')"
            @callback="selectProduct"
          />
          <!--部门选择框-->
          <select-dept
            v-if="selectDeptInfo.visible"
            v-model:show-dialog="selectDeptInfo.visible"
            :check-box="false"
            :highlight-row="true"
            :query="selectDeptInfo.query"
            :save-empty="true"
            @callback="selectDeptCallback"
          />

          <!--选择供应商-->
          <select-supplier
            v-if="selectProductSupplier.visible"
            v-model:show-dialog="selectProductSupplier.visible"
            :check-box="false"
            :highlight-row="true"
            :api="selectProductSupplier.api"
            :query="selectProductSupplier.query"
            @callback="selectSupplierCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="OtherTemplateModify">
import {
  creatOtherStoreTemplates,
  updateOtherStoreTemplates,
  getOtherStoreTemplatesById,
  getOtherStoreTemplateDetailCustomizeList,
  detailOtherStoreOrder,
  getOtherStoreOrderDetailCustomizeList,
} from '@/api/stock.js'
import { getSupplierProductPage } from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id', 'otherStoreOrderId'])

const formRefs = ref([])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
  },
  fieldList: [
    {
      label: '模板名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [
      {
        required: true,
        message: '请输入模板名称',
        trigger: 'blur',
      },
    ],
    deptName: [
      {
        required: true,
        message: '请选择部门',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    sortString: 'product_id desc',
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
  ],
})
const filterInfoOtherExport = ref({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summary: true,
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '切换供应商',
        event: changeSupplier,
        show: true,
      },
      {
        label: '删除产品',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
    deptId: '',
  },
})
const productInfo = ref({
  visible: false,
  tableKey:
    'stockOtherStoreTemplateModifyProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isConsignment: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      codeType: 3,
    },
  },
  sortString: '',
})
const selectProductSupplier = ref({
  visible: false,
  index: '',
  api: getSupplierProductPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
      row.productionDate =
        row.productionDate === '1900-01-01' ? undefined : row.productionDate
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

setData()
function setData() {
  let obj = {
    name: {
      label: '模板名称',
      value: 'name',
      show: false,
      type: 'column',
      hidden: true,
    },
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      showUnitName: true, //是否显示单位
      showQty: true, //大小单位数量输入单元格是否显示计算后的qty
      isCalculation: false, //是否计算得到大小单位最大输入值
      largeUnitQty: 'largeUnitQty',
      smallUnitQty: 'smallUnitQty',
      largeRules: [
        { validator: proxy.$validate.positive, trigger: 'blur' },
        { validator: proxy.$validate.positive, trigger: 'change' },
      ],
      smallRules: [
        { validator: proxy.$validate.positive, trigger: 'blur' },
        { validator: proxy.$validate.positive, trigger: 'change' },
      ],
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      // type: "money",
      type: 'slot',
      minWidth: '200px',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('otherTemplate:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('otherTemplate:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('otherTemplate:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
  if (!props.id) {
    formInfo.value.fieldList = formInfo.value.fieldList.filter(
      (item) => item.value !== 'id'
    )
  }
  // tableInfo.value.fieldList.forEach(item => item.hidden = false)
}
function changePrice(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
function addProduct() {
  const productIds = tableInfo.value.data.map((item) => item.productId)
  productInfo.value.query.queryMap.id.value = productIds.toString()
  if (proxy.$store.state.permission.systemConfig.is_consign_business == '0') {
    productInfo.value.query.queryMap.isConsignment.value = 0
  }
  productInfo.value.visible = true
}
//选择供应商
function changeSupplier(row, index) {
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.productId = row.productId
  selectProductSupplier.value.query.supplierIdNotIn = row.supplierId
  selectProductSupplier.value.index = index
}
//供应商返回
function selectSupplierCallback(data) {
  let index = selectProductSupplier.value.index
  let _tableInfo = tableInfo.value
  if (
    data &&
    Object.keys(data).length &&
    _tableInfo.data[index].supplierId !== data.supplierId
  ) {
    _tableInfo.data[index] = {
      ..._tableInfo.data[index],
      supplierId: data.supplierId,
      supplierName: data.supplierName,
      price: data.price,
    }
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
        productId: item.id,
        largeUnitQty: item.largeUnitQty || 0,
        smallUnitQty: item.smallUnitQty || 0,
        defaultSupplierPrice: item.price,
        defaultSupplierId: item.supplierId,
        defaultSupplierName: item.supplierName,
        defaultSupplierCode: item.supplierCode,
      }
    })
    tableInfo.value.data = tableInfo.value.data.concat(data)
  }
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.value.data['deptName'] = row.name
    formInfo.value.data['deptId'] = row.id
    tableInfo.value.data = []
  } else {
    formInfo.value.data['deptName'] = ''
    formInfo.value.data['deptId'] = ''
    tableInfo.value.data = []
  }
}
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const _formInfo = formInfo.value
    const _tableInfo = tableInfo.value
    const details = _tableInfo.data
      .filter((item) => item.productId)
      .map((item) => {
        return {
          productId: item.productId,
          calcQty: item.calcQty,
          supplierId: item.supplierId,
          price: item.price,
        }
      })
    const data = _formInfo.data
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    data.details = details
    const api = props.id ? updateOtherStoreTemplates : creatOtherStoreTemplates
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify')
      }
    })
  })
}
function getMain() {
  getOtherStoreTemplatesById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.id
  getList()
}
function getOtherExportOrderDetail() {
  detailOtherStoreOrder(props.otherStoreOrderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data.deptId = resp.data.deptId
      formInfo.value.data.deptName = resp.data.deptName
      let param = {
        tableKey:
          'stockOtherStoreOrderDetail-com.slip.spd.entity.vo.stock.OtherStoreOrderDetailVO',
      }
      getCustomizeSetting(param).then((res) => {
        if (res && res.success) {
          let data = res.data
          filterInfoOtherExport.value.query.customizeUserVO = data
          filterInfoOtherExport.value.query.queryMap.orderId.value =
            props.otherStoreOrderId
          getOtherStoreOrderDetailCustomizeList(
            filterInfoOtherExport.value.query
          ).then((resp) => {
            if (resp && resp.success) {
              const data = resp.data.map(function (item) {
                return {
                  ...item,
                  defaultSupplierPrice: item.price,
                  defaultSupplierId: item.supplierId,
                  defaultSupplierName: item.supplierName,
                  defaultSupplierCode: item.supplierCode,
                }
              })
              tableInfo.value.data = data.concat(tableInfo.value.data)
            }
          })
        }
      })
    }
  })
}
function getList() {
  getOtherStoreTemplateDetailCustomizeList(filterInfo.value.query).then(
    (res) => {
      if (res && res.success) {
        tableInfo.value.data = res.data
      }
    }
  )
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'stockOtherStoreTemplateModify-com.slip.spd.entity.vo.stock.OtherStoreOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      if (props.id) {
        getMain()
      }
      if (props.otherStoreOrderId) {
        getOtherExportOrderDetail()
      }
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
</style>
